package bai.myworld.service.impl.Shop;

import bai.myworld.common.utils.JwtUtil;
import bai.myworld.exception.BusinessException;
import bai.myworld.exception.ErrorCode;
import bai.myworld.mapper.shop.ProductMapper;
import bai.myworld.mapper.user.UserMapper;
import bai.myworld.pojo.entity.shop.Product;
import bai.myworld.pojo.entity.shop.ProductSku;
import bai.myworld.pojo.entity.shop.ProductSpecification;
import bai.myworld.pojo.entity.shop.Shop;
import bai.myworld.pojo.vo.shop.ProductDetailVO;
import bai.myworld.pojo.vo.shop.ProductSkuVO;
import bai.myworld.service.shop.ProductServiceI;
import lombok.RequiredArgsConstructor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class ProductService implements ProductServiceI {
    private static final Logger log = LogManager.getLogger(JwtUtil.class);

    // 缓存名称常量
    private static final String PRODUCT_CACHE = "productDetail";

    @Autowired
    private ProductMapper productMapper;
    // 商品详情获取（带SKU）
//    public Product getProductDetail(Long productId) {
//        return productMapper.getProductById(productId);
//    }
@Override
    public ProductDetailVO getProductDetail(Long productId) {
        // 获取产品信息
        Product product = productMapper.getProduct(productId);
        // 获取商铺信息
        Shop shop = productMapper.getShop(product.getShopId());
        // 获取产品sku
        List<ProductSku> skus = productMapper.getProductSkuList(productId);
        // 获取产品规格
        List<ProductSpecification> specifications = new ArrayList<>();
        skus.forEach(item -> {
            specifications.addAll(productMapper.getSkuSpecifications(item.getId()));
        });
        // 获取productSkuVO
        List<ProductSkuVO> productSkuVO = getProductSkuVO(specifications);

        ProductDetailVO detail = new ProductDetailVO();
        // 复制同名属性（自动匹配字段名）
        BeanUtils.copyProperties(product, detail);
        detail.setShopName(shop.getName());
        detail.setSkus(productSkuVO);
        detail.setSales(getSales(productSkuVO));
        detail.setStock(getStock(productSkuVO));


        // 异常处理
        if (product == null) {
            throw new BusinessException(ErrorCode.PRODUCT_NOT_FOUND,"商品不存在或已下架");
        }

        // 处理服务承诺（根据业务需求实现）
        enrichServices(detail);
//
        // 处理价格显示逻辑
        processPriceDisplay(detail);

        return detail;
    }

    // 商铺服务承诺
    private void enrichServices(ProductDetailVO detail) {
        // 示例数据，实际应从店铺配置或系统配置获取
        List<String> services = Arrays.asList(
                "七天无理由退货",
                "假一赔十",
                "全国包邮（偏远地区除外）"
        );
        detail.setServices(services);
    }
// 价格显示
    private void processPriceDisplay(ProductDetailVO detail) {
        // 处理价格显示逻辑（例如促销价等于原价时不显示促销价）
        if (detail.getDiscountPrice() != null &&
                detail.getDiscountPrice().compareTo(detail.getOriginalPrice()) == 0) {
            detail.setOriginalPrice(null);  // 隐藏原价显示
        }
    }
//    获取销量
    private Integer getSales( List<ProductSkuVO> productSkuVO) {
        return productSkuVO.stream()
                .mapToInt(ProductSkuVO::getSales)  // 转为 IntStream
                .sum();
    }
//    获取库存
    private Integer getStock( List<ProductSkuVO> productSkuVO) {
        return productSkuVO.stream()
                .mapToInt(ProductSkuVO::getStock)  // 转为 IntStream
                .sum();
    }

    // 获取ProducskuVO
    private List<ProductSkuVO> getProductSkuVO( List<ProductSpecification> specifications) {
        // 1. 按 skuId 分组规格数据
        Map<Long, List<ProductSpecification>> specsBySkuId = specifications.stream()
                .collect(Collectors.groupingBy(ProductSpecification::getSkuId));

// 2. 转换为 List<ProductSkuVO>
        List<ProductSkuVO> skuVOList = specsBySkuId.entrySet().stream()
                .map(entry -> {
                    Long skuId = entry.getKey();
                    List<ProductSpecification> specs = entry.getValue();

                    // 根据 skuId 查询 ProductSku（假设通过服务层获取）
                    ProductSku sku = productMapper.getProductSku(skuId);
                    if (sku == null) {
                        throw new RuntimeException("SKU not found: " + skuId);
                    }

                    // 构建 ProductSkuVO
                    ProductSkuVO skuVO = new ProductSkuVO();
                    skuVO.setId(skuId);
                    skuVO.setSkuCode(sku.getCode());  // 从 ProductSku 获取 code
                    skuVO.setPrice(sku.getPrice());   // 从 ProductSku 获取 price
                    skuVO.setSales(sku.getSold());   // 从 ProductSku 获取 stock
                    skuVO.setStock(sku.getStock());   // 从 ProductSku 获取 stock

                    // 提取规格键值对（如 {"颜色":"白色", "尺码":"S"}）
                    Map<String, String> specValues = specs.stream()
                            .collect(Collectors.toMap(
                                    ProductSpecification::getSpecType,
                                    ProductSpecification::getSpecValue,
                                    (oldVal, newVal) -> oldVal  // 重复键取旧值
                            ));
                    skuVO.setSpecValues(specValues);

                    // 提取非空的规格图片 URL（去重）
                    List<String> specImages = specs.stream()
                            .map(ProductSpecification::getSpecImageUrl)
                            .filter(Objects::nonNull)
                            .distinct()
                            .collect(Collectors.toList());
                    skuVO.setSpecImages(specImages);

                    return skuVO;
                })
                .collect(Collectors.toList());

        return skuVOList;
    }


}
